package com.ttctracker.map;


import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.readystatesoftware.mapviewballoons.BalloonItemizedOverlay;
import com.ttctracker.R;
import com.ttctracker.classes.Route;
import com.ttctracker.classes.StopItem;
import com.ttctracker.map.Map;
import com.ttctracker.map.RouteMapStopOverlayItem;
import com.ttctracker.xmlparser.SAXParserHelper;

public class RouteMapItemizedOverlay extends BalloonItemizedOverlay<OverlayItem> {

	private Map listenerActivity;
	private ArrayList<OverlayItem> routeOverlays = new ArrayList<OverlayItem>();
	private ArrayList<Route> selectedRoutes=new ArrayList<Route>();
	private OverlayItem navOverlayItem;
	private Rect currentMapBoundsRect;
	private Bitmap bmp;
	private Bitmap userLocation_icon;
	private Point currentDevicePosition;
	private SAXParserHelper stopPredictionsHelper;
	private String selectedStopTitle;
	//private StopPredictionsHandler stopPredictionsHandler;
	
	public RouteMapItemizedOverlay(Drawable defaultMarker, MapView mapView,Map listener) {
		super(boundCenter(defaultMarker), mapView);
		this.listenerActivity=listener;
		currentMapBoundsRect = new Rect();
		bmp = BitmapFactory.decodeResource(mapView.getResources(),
				R.drawable.bus_icon);
		userLocation_icon=BitmapFactory.decodeResource(mapView.getResources(),
				R.drawable.ic_gps);
		currentDevicePosition = new Point();
		stopPredictionsHelper=new SAXParserHelper(StopPredictionsHandler.class);
		try {
			stopPredictionsHelper.setup_parser();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void addOverlay(OverlayItem overlay) {
		routeOverlays.add(overlay);
		//populate();
		
	}
	
	public void clear() {
		routeOverlays.clear();
		//selectedRoutes.clear();
	}

	public void addSelectedRoute(Route route){
		//selectedRoutes.add(route);
	}
	
	@Override
	protected boolean onBalloonTap(int index) {
		Object item=routeOverlays.get(index);
		//String selectedRoute=selectedRoutes.get(0).get_tag();
		if (item.getClass()==RouteMapStopOverlayItem.class) {
			RouteMapStopOverlayItem stopOverlayItem=(RouteMapStopOverlayItem)item;
			selectedStopTitle=stopOverlayItem.getStop().get_title();
			new GetSelctedStopPredictionsTask(listenerActivity, stopPredictionsHelper).execute(stopOverlayItem.getStop().get_stopID());
			
			//Toast.makeText(listenerActivity, stopOverlayItem.getStop().get_stopID(), Toast.LENGTH_LONG).show();
			//new GetSelctedRoutePredictionsTask(listenerActivity).execute(stopOverlayItem.getStop().get_tag());
		}
		
		return super.onBalloonTap(index);
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		// TODO Auto-generated method stub
	//	super.draw(canvas, mapView, false);
		for (OverlayItem overlayItem : routeOverlays) {

			mapView.getProjection().toPixels(overlayItem.getPoint(),
					currentDevicePosition);
			mapView.getDrawingRect(currentMapBoundsRect);
			if (currentMapBoundsRect.contains(currentDevicePosition.x,
					currentDevicePosition.y)) {
				if (overlayItem.getClass() == RouteMapStopOverlayItem.class) {
					canvas.drawBitmap(bmp, currentDevicePosition.x - 10,
						currentDevicePosition.y - 10, null);
				}else {
					canvas.drawBitmap(userLocation_icon, currentDevicePosition.x - 10,
							currentDevicePosition.y - 10, null);
				}
			}
		}
	}
	
	public GeoPoint getUserLocation() {
		if (navOverlayItem!=null) {
			return navOverlayItem.getPoint();
		}
		return null;
	}

	public boolean gotUserLocation() {
		if (routeOverlays.contains(navOverlayItem)) {
			return true;
		}else {
			return false;
		}
	}
	
	public void populate_overlayItem() {
		setLastFocusedIndex(-1);
		populate();
	}
	
	public void updateNavOverlay(OverlayItem overlay) {
		
		if (navOverlayItem==null) {
			navOverlayItem=overlay;
			routeOverlays.add(navOverlayItem);
		}else {
			routeOverlays.remove(navOverlayItem);
			navOverlayItem=overlay;
			routeOverlays.add(navOverlayItem);
		}
		
		populate();
		
	}
	
	public void restoreNavOverlay() {
		if (navOverlayItem!=null&& !routeOverlays.contains(navOverlayItem)) {
			routeOverlays.add(navOverlayItem);
		}
	}
	
	@Override
	protected OverlayItem createItem(int i) {
		
			return routeOverlays.get(i);		
	}

	@Override
	public int size() {
		return routeOverlays.size();
	}
	
	private class GetSelctedStopPredictionsTask extends AsyncTask<String, Void, HashMap<String, StopItem>>{
		
		private ProgressDialog progressDialog;
		private String stopId;
		private SAXParserHelper stopPredictionsHelper;
		private StopPredictionsHandler stopPredictionsHandler;
		private Map listener;
		
		private GetSelctedStopPredictionsTask(Map listenerActivity, SAXParserHelper helper){
			this.listener=listenerActivity;
			this.stopPredictionsHelper=helper;
		}
		
		@Override
		protected void onPreExecute() {
			progressDialog=new ProgressDialog(listener);
			progressDialog.setMessage("Retrieving prediction data...");
			progressDialog.show();
		}

		@Override
		protected HashMap<String, StopItem> doInBackground(String... params) {
			try {
				//selectedRoute=params[0];
				stopId=params[0];

				URL url = new URL(
						"http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=ttc&stopId="+stopId);

				// perform the synchronous parse
				stopPredictionsHelper.setInputStream(url.openStream());
				
				stopPredictionsHelper.parseXml();
				stopPredictionsHandler=(StopPredictionsHandler) stopPredictionsHelper.getHandler();
				// get the results - should be a fully populated stop prediction data
				// or null on error
				return stopPredictionsHandler.getStopItems();
			} catch (Exception e) {
				// if you have a problem, simply return null
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(HashMap<String, StopItem> result) {
			progressDialog.dismiss();
			
			if (result!=null) {
				Intent intent=new Intent(listenerActivity,ViewStopPredictions.class);
				intent.putExtra("stopID", stopId);
				intent.putExtra("stopTitle", selectedStopTitle);
				intent.putExtra("stopItems", result);
				listenerActivity.startActivity(intent);
			}else {
				AlertDialog.Builder builder = new AlertDialog.Builder(listener);
				builder.setMessage("Cannot retrieve TTC bus prediction data, make sure you have network connection.")
			       .setCancelable(false)
			       .setPositiveButton("Close", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
				AlertDialog alert = builder.create();
				alert.show();
			}
			
			/*Prediction predictions=result.get_prediction();
			int prediction =predictions.get(0);
			
			String predictionTextString=Integer.toString(prediction)+" Min";
			
			if (prediction<0) {
				predictionTextString="Prediction Not Avaliable";
				//((TextView)row.findViewById(R.id.predictionLabel)).setText("Prediction Not Avaliable");
			}
			if (predictions.size()>1) {
				predictionTextString+=", "+Integer.toString(predictions.get(1))+" Min";//+Integer.toString(predictions.get(2))+" Min";
			}*/
			
			/*builder.setMessage(result.size()+"\n\n")
			       .setCancelable(false)
			       .setPositiveButton("Close", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();*/
		}
		
	}

	
	
	
}
